const sequelize = require('../config/database');
const logger = require('../utils/logger');

async function fixOrdersTable() {
  try {
    // 检查orders表的索引数量
    const [indexes] = await sequelize.query(`
      SELECT COUNT(*) as index_count 
      FROM information_schema.statistics 
      WHERE table_schema = DATABASE() 
      AND table_name = 'orders'
    `);
    
    const indexCount = indexes[0].index_count;
    logger.info(`Orders表当前有 ${indexCount} 个索引`);
    
    if (indexCount >= 60) {
      logger.warn('索引数量过多，开始清理...');
      
      // 获取所有索引
      const [allIndexes] = await sequelize.query(`
        SELECT DISTINCT index_name 
        FROM information_schema.statistics 
        WHERE table_schema = DATABASE() 
        AND table_name = 'orders'
        AND index_name != 'PRIMARY'
      `);
      
      // 删除非必要索引（保留主键和外键）
      for (const index of allIndexes) {
        const indexName = index.index_name;
        
        // 保留重要索引
        if (!['PRIMARY', 'userId', 'orderNumber'].includes(indexName)) {
          try {
            await sequelize.query(`DROP INDEX \`${indexName}\` ON orders`);
            logger.info(`已删除索引: ${indexName}`);
          } catch (error) {
            logger.warn(`删除索引 ${indexName} 失败:`, error.message);
          }
        }
      }
      
      logger.info('索引清理完成');
    }
    
  } catch (error) {
    logger.error('修复orders表失败:', error);
    throw error;
  }
}

module.exports = fixOrdersTable;

// 如果直接运行此脚本
if (require.main === module) {
  fixOrdersTable()
    .then(() => {
      console.log('Orders表修复完成');
      process.exit(0);
    })
    .catch((error) => {
      console.error('修复失败:', error);
      process.exit(1);
    });
}